<template>
	<view>
		<view class="content">
			<uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules">
				<uni-forms-item label="IP地址" required name="ip">
					<uni-easyinput v-model="baseFormData.ip" placeholder="请输入xxx.xxx.xxx.xxx格式" />
				</uni-forms-item>
				<uni-forms-item label="端口号" required name="port">
					<uni-easyinput v-model="baseFormData.port" placeholder="请输入5位以内的数字" />
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="submit('baseForm')">确认</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseFormData:{
					ip:'',
					port:''
				},
				rules: {
					ip: {
						rules: [{
							required: true,
							errorMessage: '请输入IP地址'
						}]
					},
					port: {
						rules: [{
							required: true,
							errorMessage: '请输入端口号'
						}]
					}
				},
				ip:getApp().globalData.config.ip,
				port:getApp().globalData.config.port,
			}
		},
		
		mounted(){
			//显示加载框
			uni.showLoading({
				title: "加载中",
				mask:true
			});
			var ip ='';
			var port ='';
			try{
				ip = uni.getStorageSync('ip');
				if(ip == null || ip == '' ){
					this.baseFormData.ip = this.ip;
				}else{
					this.baseFormData.ip = ip;
				}
				port = uni.getStorageSync('port');
				if(port == null || port == ''){
					this.baseFormData.port = this.port;
				}else{
					this.baseFormData.port = port;
				}
			}catch(e){
				console.log('err', e.message);	
			}
			//隐藏加载框
			uni.hideLoading();
		},
		
		methods: {
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					//显示加载框
					uni.showLoading({
						title: "加载中",
						mask:true
					});
					var regIp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
					if(!regIp.test(this.baseFormData.ip)){
						//隐藏加载框
						uni.hideLoading();
						uni.showToast({
							title: '请输入正确的IP地址',
							icon: 'none',
							duration: 5000
						});
						return;
					}
					const regPort = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/;
					if(!(this.baseFormData.port.length > 0 && this.baseFormData.port.length <= 5 && regPort.test(this.baseFormData.port))){
						//隐藏加载框
						uni.hideLoading();
						uni.showToast({
							title: '请输入正确的端口号',
							icon: 'none',
							duration: 5000
						});
						return;
					}
					try{
						uni.setStorageSync('ip', this.baseFormData.ip);
						uni.setStorageSync('port', this.baseFormData.port);
					}catch(e){
						console.log('err', e.message);					
					}
					//隐藏加载框
					uni.hideLoading();
					uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
					    delta: 1
					});
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style>
	.content{
		margin-top:  50px;
		margin-left: 10px;
		margin-right: 10px;
	}
</style>
